/**
 * @author HuangWenJing
 */

(function() {

	var autoInputs = [];

	$.autoInput = {
		/**
		 * 更新所有模块的输入框
		 */
		moduleUpdate : function() {
			for ( var i in autoInputs) {
				var input = $(autoInputs[i]);
				var option = input.getAutoOpt();
				var updDiagram = option.updDiagram;
				if (updDiagram.enable) {
					input.updAutoInput(option.isFresh);
				}
			}
		}
	};

	/**
	 * 自动完成初始化函数
	 */
	$.fn.autoInput = function(options) {
		this.each(function() {

			var self = this;
			options = $.extend(true, {
				url : jsContextPath + '/select/getAutoInput.do',
				reportId : '',
				postData : {},
				isFresh : false,
				formId : null,
				callBack : null,
				isClearAll : false,// 清空输入框是否要加载后台数据
				defLabel : {
					value : '',// 真实值
					label : ''// 显示的值
				},
				updDiagram : {
					enable : false,
					handler : updDiagram
				},
				paging : {
					enable : true,
					pageSize : 50,
					startIndex : 0
				}
			}, options || {});

			// 缓存配置
				self.autoOpts = options;

				// 设置默认值
				var inputVal = $(self).val();
				var hidden = $(self).getRealInput(), hiddenVal = hidden.val();
				if (inputVal) {
					options.defLabel.label = inputVal;
				}

				if (hiddenVal) {
					options.defLabel.value = hiddenVal;
				}

				// 将输入框放到数组里面
				if (options.isFresh) {
					autoInputs.push(this);
				}
				// 设置输入框的默认值
				setDefLabel($(self), options.defLabel);

				// 后台获取结果集
				$(self).autocompletebox(
						{
							source : function(request, response) {
								$.ajax( {
									url : options.url,
									dataType : 'json',
									type : 'post',
									data : setPostData(self, options),
									success : function(data, status) {

										var autoinput = data.autoInput || [];
										response($.ui.autocomplete.filter(
												autoinput, request.term));

										// 执行回调函数
										if ($.isFunction(options.callBack)) {
											options.callBack.call(self, data);
										}
									},
									beforeSend : function() {
										clearText($(self), hidden);
										var value = $(self).val();
										if (!value || !$.trim(value)) {
											// 不向后台发送请求
									if (options.isClearAll) {
										this.url = '';
									}
									// 清空后，真实值设为空
									hidden.val('');
								}

							}
								})
							}
						});

				// 绑定select事件
				$(self).on('autocompleteselect', function(event, ui) {
					var hidden = $(this).getRealInput();
					hidden.val(ui.item.value);
					$.utils.widgetLinkage(hidden);

					var autoOpts = this.autoOpts || {};
					var updDiagram = autoOpts.updDiagram;
					if (updDiagram.enable) {
						var handler = updDiagram.handler;
						if ($.isFunction(handler)) {
							handler.call(this);
						}
					}

				});
			});

	};

	$.fn.extend( {
		/**
		 * 获取真实值控件
		 */
		getRealInput : function() {
			var input = this;
			var id = input.attr('id');
			var hidden = input.parents('div').find('input[for="' + id + '"]');

			return hidden;
		},
		/**
		 * 获取输入框配置
		 */
		getAutoOpt : function() {
			var autoOpts = this[0].autoOpts;
			return autoOpts || {};
		},
		updAutoInput : function(isFresh) {
			// 先清空
		this.val('');
		var hidden = this.getRealInput();
		hidden.val('');

		var option = this.getAutoOpt();
		if (isFresh) {
			var defLabel = option.defLabel;
			// 设置默认值
		this.val(defLabel.label);
		hidden.val(defLabel.value);
	}
}
	});

	/**
	 * 刷新图表
	 */
	function updDiagram() {
		var container = $(this).parents('div.panel');

		var charts = container.find('.chart');
		var grids = container.find('.grid');
		var form = container.find('form');

		var postData = $.utils.formArrayToObj(form);

		$(charts).updateChart( {
			params : postData
		});

		grids.each(function() {
			$(this).jqGrid('setGridConfig', {
				paramObj : postData
			});
			$(this).doFind();
		});
	}
	;

	/**
	 * 设置后台参数
	 */
	function setPostData(input, options) {

		// 获取输入框的值
		input = $(input);
		options.postData[input.attr('id')] = input.val();

		// 设置reportId
		options.postData.reportId = options.reportId;
		// 获取表单数据
		var formData = $.utils.formArrayToObj($('#' + options.formId));
		options.postData = $.extend(true, options.postData, formData);

		// 根据级联来筛选选项
		var masters = input.attr('masters') || '';
		masters = masters.split(';');

		for ( var i in masters) {
			var key = masters[i];
			options.postData[key] = $('#' + key).val();
		}

		var paging = options.paging;

		options.postData.paging = paging.enable;
		options.postData.pageSize = paging.pageSize;
		options.postData.startIndex = paging.startIndex;

		return options.postData;
	}
	;

	/**
	 * 设置默认值
	 */
	function setDefLabel(input, defLabel) {
		// 设置输入框值
		var label = defLabel.label, value = defLabel.value;
		input.val(decodeURI(label));
		// 设置真实值
		var hidden = input.getRealInput();
		hidden.val(decodeURI(value));
	}
	;

	/**
	 * 清除输入框、hidden值
	 */
	function clearText(input, hidden) {

		var showClear = input.attr('showClear');
		if ('1' != showClear) {
			var clear = input.parent().find('button.clearText');
			clear[0].target = hidden;
			clear[0].autoInput = input[0];
			clear
					.click(function() {
						var target = $(this)[0].target, autoInput = $(this)[0].autoInput;

						$(target).val('');
						var autoOpts=autoInput.autoOpts||{};
						var updDiagram = autoOpts.updDiagram;
						if(updDiagram.enable){
							var handler = updDiagram.handler;
							if ($.isFunction(handler)) {
								handler.call($(autoInput));
							}
						}
					});

			input.attr('showClear', '1');
		}
	}
	;

})();